/*************************************************************************
	> File Name: fork_race.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Sun 06 Jul 2014 07:42:55 PM CST
 ************************************************************************/

#include"head.h"
//演示了 fork 中 父子 进程的竞争现象 
int main(int argc,char *argv[])
{
    int howmanychildern;
    pid_t child;
    int j;
    
    if(argc>2)
    {
        printf("%s number\n",argv[0]);
        exit(0);
    }
    howmanychildern=(argc>1)?atoi(argv[1]):1;

    setbuf(stdout,NULL); // make stdout unbuffered

    for(j=0;j<howmanychildern;j++)
    {
        switch(child=fork()){
            case -1:
                err("fork");
            case 0:
                printf("%d-->:child\n",j);
                //break; // don't use this
                _exit(0);
            default:
                printf("%d-->:\e[32mparent\e[0m\n",j);
                wait(NULL); // wait child to exit
                break;
        }
    }
    exit(0);
}
